package com.googlecode.restitory.gae.rhino;

import java.io.CharArrayReader;
import java.io.IOException;
import java.net.URL;

import org.mozilla.javascript.Context;
import org.mozilla.javascript.Function;
import org.mozilla.javascript.Scriptable;
import org.mozilla.javascript.ScriptableObject;

import com.googlecode.mycontainer.commons.io.IOUtil;

public class RhinoUtil {

	public static void config(ScriptableObject scope) {
		scope.defineFunctionProperties(new String[] { "load" }, RhinoUtil.class, 0);
	}

	public static Object load(Context cx, Scriptable thisObj, Object[] args, Function funObj) {
		try {
			String path = (String) args[0];
			URL url = RhinoUtil.class.getClassLoader().getResource(path);
			if (url == null) {
				throw new RuntimeException("not found: " + path);
			}
			char[] chars = IOUtil.readChars(url);
			Object ret = cx.evaluateReader(thisObj, new CharArrayReader(chars), url.toString(), 1, null);
			return ret;
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
	}

}
